package com.ruoyi.common.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.constant.ReceivedMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.ResponseEntity;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.util.Collections;

public class DeepLTranslationUtil {
    private static final Logger log = LoggerFactory.getLogger(DeepLTranslationUtil.class);

    private static final ObjectMapper objectMapper = new ObjectMapper();


    private static final String apiKey = "c39c363b-fbd8-4a2d-98d2-edde91510687:fx";
    private static final RestTemplate restTemplate = new RestTemplate();

    private DeepLTranslationUtil() {
    }

    public static String translate(String text, String targetLanguage) {
        try {
//            Environment env = SpringUtils.getBean(Environment.class);
//            String url = env.getProperty("apiSevicePath.deelpapp");
            String url = "https://api-free.deepl.com/v2/translate";

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("auth_key", apiKey);
            map.add("text", text);
            map.add("target_lang", targetLanguage);

            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

            ResponseEntity<Map> response = restTemplate.postForEntity(url, request, Map.class);

            Map<String, Object> responseBody = response.getBody();
            if (responseBody != null && responseBody.containsKey("translations")) {
                List<Map<String, String>> translations = (List<Map<String, String>>) responseBody.get("translations");
                if (!translations.isEmpty()) {
                    return translations.get(0).get("text");
                }
            }
        } catch (Exception e) {
            log.error("翻译出错", e);
        }

        return "Translation failed.";
    }


    public static int postMessage(ReceivedMessage receivedMessage,String url,String chatId ) {
        try {
            RestTemplate restTemplate = new RestTemplate();
            String language = receivedMessage.getTargetLanguage();
            if (StringUtils.isEmpty(language)) {
                language = TranslateUtils.trsLang(receivedMessage.getToNumber());
            }
            log.info("收到消息 - from: {},to：{}， 类型: {}, 内容: {}，翻译：{}",
                    receivedMessage.getFromNumber(),
                    receivedMessage.getToNumber(),
                    receivedMessage.getMessageType(),
                    receivedMessage.getMessage(),
                    language);
            String transMessage = DeepLTranslationUtil.translate(receivedMessage.getMessage(), language);

            // 构建请求体
            Map<String, String> body = new HashMap<>();
            body.put("id", receivedMessage.getFromNumber());
            body.put("number", receivedMessage.getToNumber() + "@c.us");
            body.put("messageType", receivedMessage.getMessageType());
            body.put("messageText", transMessage);
            body.put("from", "1");
            body.put("chatId", chatId);

            // 发送 POST 请求
            ResponseEntity<String> response = restTemplate.postForEntity(url, body, String.class);

            return 1;

        } catch (Exception e) {
            log.error("e", e);
            return 0;
        }
    }

    public static void postMessage(String fromNumber, String toNumber, String message, String targetLanguage,String url,String chatid) {
        ReceivedMessage receivedMessage = new ReceivedMessage();
        receivedMessage.setFromNumber(fromNumber);
        receivedMessage.setToNumber(toNumber);
        receivedMessage.setMessage(message);
        receivedMessage.setMessageType("0");
        receivedMessage.setTargetLanguage(targetLanguage);
        postMessage(receivedMessage,url,chatid);
    }

    public static void main(String[] args) {
        System.out.println(translate("你好", "PT-BR"));
    }
}